import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../models/todo_item.dart';

/// 待办列表组件
class TodoListWidget extends StatelessWidget {
  final List<TodoItem> todoList;
  final TodoItem? selectedTodo;
  final Function(TodoItem) onTodoItemTap;
  final Function(String)? onCategoryTap; // 点击分类名的回调

  const TodoListWidget({
    super.key,
    required this.todoList,
    required this.selectedTodo,
    required this.onTodoItemTap,
    this.onCategoryTap,
  });

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      padding: const EdgeInsets.all(8),
      itemCount: todoList.length,
      separatorBuilder: (context, index) => Divider(
        height: 1,
        thickness: 1,
        indent: 16,
        endIndent: 16,
        color: Colors.grey[300],
      ),
      itemBuilder: (context, index) {
        final todo = todoList[index];
        final isSelected = selectedTodo?.id == todo.id;
        final isCompleted = todo.status == 'completed';

        // iOS平台不支持拖拽，直接返回卡片
        if (Platform.isIOS) {
          return _buildTodoCard(todo, isSelected, isCompleted);
        }

        // macOS平台支持拖拽
        final contentLines = _extractContentLines(todo.content);
        final firstLine = contentLines['firstLine'];

        return Draggable<TodoItem>(
          data: todo,
          feedback: Material(
            elevation: 8,
            child: Container(
              width: 280,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.blue, width: 2),
              ),
              child: Text(
                firstLine ?? '无标题',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  decoration: isCompleted ? TextDecoration.lineThrough : null,
                  color: isCompleted ? Colors.grey : null,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          childWhenDragging: Opacity(
            opacity: 0.3,
            child: Container(
              margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 0),
              padding: const EdgeInsets.symmetric(vertical: 2),
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(10),
              ),
              child: Stack(
                children: [
                  ListTile(
                    selected: false,
                    selectedTileColor: Colors.transparent,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 4,
                    ),
                    title: Text(
                      firstLine ?? '无标题',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                        decoration: isCompleted ? TextDecoration.lineThrough : null,
                        color: isCompleted ? Colors.grey[600] : null,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    subtitle: (todo.categoryName != null || contentLines['remainingLines'] != null || todo.createdTime != null)
                        ? Padding(
                            padding: const EdgeInsets.only(top: 4),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // 显示分类名称和创建时间（同一行，一左一右）
                                if (todo.categoryName != null || todo.createdTime != null)
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 2),
                                    child: Row(
                                      children: [
                                        // 分类名称（可点击）
                                        if (todo.categoryName != null)
                                          Expanded(
                                            child: _buildCategoryName(todo),
                                          ),
                                        // 创建时间
                                        if (todo.createdTime != null)
                                          Text(
                                            _formatCreatedTime(todo.createdTime),
                                            style: TextStyle(
                                              fontSize: 11,
                                              color: Colors.grey[500],
                                            ),
                                          ),
                                      ],
                                    ),
                                  ),
                                // 显示剩余内容
                                if (contentLines['remainingLines'] != null)
                                  Text(
                                    contentLines['remainingLines']!,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: isCompleted ? Colors.grey[500] : Colors.grey[600],
                                      decoration: isCompleted ? TextDecoration.lineThrough : null,
                                    ),
                                  ),
                              ],
                            ),
                          )
                        : null,
                  ),
                  // 右上角图标区域（关注图标 + 置顶图标）
                  Positioned(
                    top: 6,
                    right: 8,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 关注图标
                        if (todo.isFavorite)
                          Padding(
                            padding: const EdgeInsets.only(right: 4),
                            child: Icon(
                              Icons.favorite,
                              size: 14,
                              color: Colors.red[400],
                            ),
                          ),
                        // 置顶图标
                        if (todo.isTop)
                          SvgPicture.asset(
                            'assets/icons/top.svg',
                            width: 16,
                            height: 16,
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          child: _buildTodoCard(todo, isSelected, isCompleted),
        );
      },
    );
  }

  /// 提取第一行和剩余内容
  Map<String, String?> _extractContentLines(String? content) {
    if (content == null || content.isEmpty) {
      return {'firstLine': null, 'remainingLines': null};
    }

    final lines = content.split('\n');
    final firstLine = lines.first.trim();

    if (lines.length > 1) {
      final remainingLines = lines.sublist(1).join('\n').trim();
      return {
        'firstLine': firstLine.isEmpty ? null : firstLine,
        'remainingLines': remainingLines.isEmpty ? null : remainingLines,
      };
    }

    return {
      'firstLine': firstLine.isEmpty ? null : firstLine,
      'remainingLines': null,
    };
  }

  /// 格式化创建时间
  String _formatCreatedTime(DateTime? createdTime) {
    if (createdTime == null) return '';

    final now = DateTime.now();
    final difference = now.difference(createdTime);

    // 今天：显示具体时间 HH:mm
    if (difference.inDays == 0 && now.day == createdTime.day) {
      return '${createdTime.hour.toString().padLeft(2, '0')}:${createdTime.minute.toString().padLeft(2, '0')}';
    }

    // 昨天
    if (difference.inDays == 1 || (difference.inDays == 0 && now.day != createdTime.day)) {
      return '昨天';
    }

    // 一周内：显示星期几
    if (difference.inDays < 7) {
      const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      return weekdays[createdTime.weekday - 1];
    }

    // 今年：显示月-日
    if (now.year == createdTime.year) {
      return '${createdTime.month}-${createdTime.day}';
    }

    // 其他：显示年-月-日
    return '${createdTime.year}-${createdTime.month}-${createdTime.day}';
  }

  /// 构建分类名称显示（可点击）
  Widget _buildCategoryName(TodoItem todo) {
    if (todo.categoryName == null) {
      return const SizedBox.shrink();
    }

    // 如果提供了回调且有分类ID，则包装为可点击的
    if (onCategoryTap != null && todo.categoryId != null) {
      return Row(
        children: [
          GestureDetector(
            onTap: () => onCategoryTap!(todo.categoryId!),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.folder_outlined,
                  size: 12,
                  color: Colors.grey[500],
                ),
                const SizedBox(width: 4),
                Text(
                  todo.categoryName!,
                  maxLines: 1,
                  overflow: TextOverflow.clip,
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
        ],
      );
    }

    // 不可点击时的显示
    return Row(
      children: [
        Icon(
          Icons.folder_outlined,
          size: 12,
          color: Colors.grey[500],
        ),
        const SizedBox(width: 4),
        Expanded(
          child: Text(
            todo.categoryName!,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 11,
              color: Colors.grey[500],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建待办卡片
  Widget _buildTodoCard(TodoItem todo, bool isSelected, bool isCompleted) {
    final contentLines = _extractContentLines(todo.content);
    final firstLine = contentLines['firstLine'];
    final remainingLines = contentLines['remainingLines'];

    return Container(
      margin: EdgeInsets.only(
        top: isSelected ? 0 : 4,
        bottom: isSelected ? 0 : 4,
        left: isSelected ? 0 : 8,
        right: isSelected ? 0 : 8,
      ),
      padding: EdgeInsets.symmetric(vertical: isSelected ? 6 : 2),
      decoration: BoxDecoration(
        color: isSelected ? const Color(0xFFE8E8E8) : Colors.transparent,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Stack(
        children: [
          ListTile(
            selected: isSelected,
            selectedTileColor: Colors.transparent,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 4,
            ),
            title: Text(
              firstLine ?? '无标题',
              style: TextStyle(
                fontSize: 14,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                decoration: isCompleted ? TextDecoration.lineThrough : null,
                color: isCompleted ? Colors.grey[600] : null,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: (todo.categoryName != null || remainingLines != null || todo.createdTime != null)
                ? Padding(
                    padding: const EdgeInsets.only(top: 4),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 显示分类名称和创建时间（同一行，一左一右）
                        if (todo.categoryName != null || todo.createdTime != null)
                          Padding(
                            padding: const EdgeInsets.only(bottom: 2),
                            child: Row(
                              children: [
                                // 分类名称（可点击）
                                if (todo.categoryName != null)
                                  Expanded(
                                    child: _buildCategoryName(todo),
                                  ),
                                // 创建时间
                                if (todo.createdTime != null)
                                  Text(
                                    _formatCreatedTime(todo.createdTime),
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: Colors.grey[500],
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        // 显示剩余内容
                        if (remainingLines != null)
                          Text(
                            remainingLines,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 12,
                              color: isCompleted ? Colors.grey[500] : Colors.grey[600],
                              decoration: isCompleted ? TextDecoration.lineThrough : null,
                            ),
                          ),
                      ],
                    ),
                  )
                : null,
            onTap: () => onTodoItemTap(todo),
          ),
          // 右上角图标区域（关注图标 + 置顶图标）
          Positioned(
            top: isSelected ? 10 : 6,
            right: 8,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 关注图标
                if (todo.isFavorite)
                  Padding(
                    padding: const EdgeInsets.only(right: 4),
                    child: Icon(
                      Icons.favorite,
                      size: 14,
                      color: Colors.red[400],
                    ),
                  ),
                // 置顶图标
                if (todo.isTop)
                  SvgPicture.asset(
                    'assets/icons/top.svg',
                    width: 16,
                    height: 16,
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

}
